package com.lgh.demo.viewModel;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.lgh.demo.MyApplication;
import com.lgh.demo.R;
import com.lgh.demo.activity.PayActivity;
import com.lgh.demo.activity.SubmitActivity;
import com.lgh.demo.bean.BeanHistoryOrder;
import com.lgh.demo.databinding.ActivitySubmitBinding;
import com.lgh.demo.databinding.ItemFoodSelectBinding;
import com.lgh.demo.util.ActivityUtils;
import com.lgh.demo.util.ApiUtils;
import com.lgh.demo.util.DensityHelper;
import com.lgh.demo.util.Tools;
import com.lgh.demo.util.WMConstantUtil;
import com.lgh.demo.view.BorderView;
import com.sankuai.waimai.opensdk.MTWMApi;
import com.sankuai.waimai.opensdk.callback.LoadDataListener;
import com.sankuai.waimai.opensdk.request.model.PayLoad;
import com.sankuai.waimai.opensdk.response.model.FoodItem;
import com.sankuai.waimai.opensdk.response.model.PayParams;
import com.sankuai.waimai.opensdk.response.model.preview.PreviewOrder;
import com.sankuai.waimai.opensdk.response.model.submit.SubmitOrder;

import java.util.ArrayList;
import java.util.List;

public class VMSubmit {

    private SubmitActivity submitActivity;
    private ActivitySubmitBinding submitBinding;
    private PreviewOrder previewOrder;
    private BorderView borderView;
    private String poiImg;

    public VMSubmit(SubmitActivity submitActivity, ActivitySubmitBinding submitBinding, PreviewOrder data, String poiImg) {
        this.submitActivity = submitActivity;
        this.submitBinding = submitBinding;
        this.previewOrder = data;
        this.poiImg = poiImg;

        addSelectFoodView();
        initBorderView();
    }

    private void initBorderView() {
        borderView = new BorderView(submitActivity);
        borderView.setBackgroundResource(R.drawable.focus_default);
        borderView.attachTo(submitBinding.llMain);
    }

    private void addSelectFoodView() {
        for (int i = 0; i < previewOrder.getPreviewFoodItemList().size(); i++) {
            ItemFoodSelectBinding itemFoodBinding = DataBindingUtil.inflate(LayoutInflater.from(submitActivity),
                    R.layout.item_food_select, null, false);
            View view = itemFoodBinding.getRoot();
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams((int) DensityHelper.pt2px(submitActivity, 570),
                    (int) DensityHelper.pt2px(submitActivity, 110));
            params.topMargin = i / 2 * (int) DensityHelper.pt2px(submitActivity, 125);
            params.leftMargin = i % 2 * (int) DensityHelper.pt2px(submitActivity, 630);
            submitBinding.flContent.addView(view, params);

            itemFoodBinding.setFoodItem(previewOrder.getPreviewFoodItemList().get(i));
            view.setTag(itemFoodBinding);
        }
    }

    public void commitOrder(View view) {
        submitWithCheck();
        addHistoryOrder();
    }

    private void addHistoryOrder() {
        String historyStr = Tools.getStringPreference(submitActivity, WMConstantUtil.KEY_HISTORY_ORDER);
        List<BeanHistoryOrder> historyOrders = JSONObject.parseArray(historyStr, BeanHistoryOrder.class);
        if (historyOrders == null) {
            historyOrders = new ArrayList<>();
        }
        BeanHistoryOrder beanHistoryOrder = new BeanHistoryOrder();
        BeanHistoryOrder.PreviewOrderBean previewOrderBean = JSON.parseObject(JSONObject.toJSONString(previewOrder),
                new TypeReference<BeanHistoryOrder.PreviewOrderBean>() {
                });
        beanHistoryOrder.setPreviewOrder(previewOrderBean);
        beanHistoryOrder.setPoiImg(poiImg);
        historyOrders.add(beanHistoryOrder);
        Tools.setStringPreference(submitActivity, WMConstantUtil.KEY_HISTORY_ORDER, JSON.toJSONString(historyOrders));
    }

    private void submitWithCheck() {
        PayLoad submitPayload = createSubmitPayLoad();
        LoadDataListener<SubmitOrder> loadDataListener = new LoadDataListener<SubmitOrder>() {
            @Override
            public void onSuccess(SubmitOrder data) {
                if (data != null) {
                    if (data.getCode() == 0 && !TextUtils.isEmpty(data.getCashierUrl()) && data.getPayParams() != null) {
                        gotoPay(data.getCashierUrl(), data.getPayParams(), data.getOrderId());
                    } else {
                        handleErrorCode(data.getCode());
                    }

                }
            }

            @Override
            public void onError(String errorMsg) {
                Toast.makeText(submitActivity, errorMsg, Toast.LENGTH_LONG).show();
            }
        };

        MTWMApi.submitOrder(submitPayload, loadDataListener);

    }

    private void gotoPay(String payUrl, PayParams payParams, long orderId) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(payUrl);
        stringBuilder.append("?");

        if (!TextUtils.isEmpty(payParams.getPayToken()) && !"null".equals(payParams.getPayToken())) {
            stringBuilder.append("pay_token=" + payParams.getPayToken());
        }
        if (!TextUtils.isEmpty(payParams.getTradeNo()) && !"null".equals(payParams.getTradeNo())) {
            stringBuilder.append("&tradeno=" + payParams.getTradeNo());
        }
        if (!TextUtils.isEmpty(payParams.getToken()) && !"null".equals(payParams.getToken())) {
            stringBuilder.append("token=" + payParams.getToken());
        }
        if (!TextUtils.isEmpty(payParams.getNeedLogin()) && !"null".equals(payParams.getNeedLogin())) {
            stringBuilder.append("&needLogin=" + payParams.getNeedLogin());
        }

        if (!TextUtils.isEmpty(payParams.getNbPlatform()) && !"null".equals(payParams.getNbPlatform())) {
            stringBuilder.append("&nb_platform=" + payParams.getNbPlatform());
        }

        if (!TextUtils.isEmpty(payParams.getNbVersion()) && !"null".equals(payParams.getNbVersion())) {
            stringBuilder.append("&nb_version=" + payParams.getNbVersion());
        }

        if (!TextUtils.isEmpty(payParams.getAuth()) && !"null".equals(payParams.getAuth())) {
            stringBuilder.append("&auth=" + payParams.getAuth());
        } else {
            stringBuilder.append("&auth=v2");
        }

        String url = stringBuilder.toString();
        Intent intent = new Intent(submitActivity, PayActivity.class);
        intent.putExtra(WMConstantUtil.KEY_cashier_url, url);
        intent.putExtra(WMConstantUtil.KEY_ORDER_ID, orderId+"");
        intent.putExtra(WMConstantUtil.KEY_pay_sucess_url, ApiUtils.getMyUrl(ApiUtils.Pay_Sucess_URL) + orderId + "&CANO="
                + MyApplication.beanLocationInfo.getResult().getCANO());
        ActivityUtils.gotoActivityWithIntent(submitActivity, intent);
    }

    public PayLoad createSubmitPayLoad() {
        PayLoad payLoad = new PayLoad();
        payLoad.setPaySource("3");

        payLoad.setReturnUrl(ApiUtils.getMyUrl(ApiUtils.Pay_Sucess_URL));
        payLoad.setUserPhone(MyApplication.beanLocationInfo.getResult().getPhone());
        payLoad.setSubmit(true);
        PayLoad.WmOrderingList orderingList = new PayLoad.WmOrderingList();
        payLoad.setWmOrderingList(orderingList);
        orderingList.setWmPoiId(previewOrder.getOrderSummary().getPoiId());
        orderingList.setDeliveryTime(0);
        orderingList.setPayType(2);
        List<PayLoad.FoodItem> foodItemList = new ArrayList<>();

        for (int i = 0; i < previewOrder.getPreviewFoodItemList().size(); i++) {
            FoodItem foodItem = previewOrder.getPreviewFoodItemList().get(i);
            PayLoad.FoodItem payLoadItem = new PayLoad.FoodItem();
            payLoadItem.setCount(foodItem.getCount());
            payLoadItem.setWmFoodSkuId(foodItem.getFoodSkuId());
            foodItemList.add(payLoadItem);
        }
        orderingList.setFoodList(foodItemList);

        PayLoad.WmOrderingUser user = new PayLoad.WmOrderingUser();
        user.setUserPhone(MyApplication.beanLocationInfo.getResult().getPhone());
        user.setUserName(MyApplication.beanLocationInfo.getResult().getName());
        user.setUserAddress(MyApplication.beanLocationInfo.getResult().getAddress());
        user.setAddrLongtitude(MyApplication.longtitude);
        user.setAddrLatitude(MyApplication.latitude);
//        user.setAddrLongtitude(Integer.parseInt(MyApplication.beanLocationInfo.getResult().getLongitude()));  //todo  记得加上
//        user.setAddrLatitude(Integer.parseInt(MyApplication.beanLocationInfo.getResult().getLatitude()));
        user.setUserCaution("");

        payLoad.setWmUserInfo(user);

        return payLoad;
    }

    /**
     * 异常code处理
     * 订单状态码:0:成功 1:失败 2:重复下单 3:商家不可买 4:菜品不可买 5:预计送达时间错误 6:菜品未达起送数金额 8:订单被风控拦截
     * 9:超出配送范围 11:超出价格上限 15:未达到菜品最小起送份数 17:配送费已经变化 20:缺少必选菜品 31:菜品为空
     * 36:商家不支持当前支付方式 其他:系统升级,稍后重试
     *
     * @param code
     */
    private void handleErrorCode(int code) {
        if (code == 0) {
            return;
        }
        String errorMsg = "系统升级,稍后重试";
        switch (code) {
            case 1:
                errorMsg = "失败";
                break;
            case 2:
                errorMsg = "重复下单";
                break;
            case 3:
                errorMsg = "商家不可买";
                break;
            case 4:
                errorMsg = "菜品不可买";
                break;
            case 5:
                errorMsg = "预计送达时间错误";
                break;
            case 6:
                errorMsg = "菜品未达起送数金额";
                break;
            case 8:
                errorMsg = "订单被风控拦截";
                break;
            case 9:
                errorMsg = "超出配送范围";
                break;
            case 11:
                errorMsg = "超出价格上限";
                break;

            case 15:
                errorMsg = "未达到菜品最小起送份数";
                break;
            case 17:
                errorMsg = "配送费已经变化";
                break;
            case 20:
                errorMsg = "缺少必选菜品";
                break;
            case 31:
                errorMsg = "菜品为空";
                break;
            case 36:
                errorMsg = "商家不支持当前支付方式";
                break;
            default:
                errorMsg = "系统升级,稍后重试";
                break;
        }
        Toast.makeText(submitActivity, errorMsg, Toast.LENGTH_LONG).show();
    }

}
